package net.youpo.Market.UI.HomePage;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import net.youpo.Market.BaseActivity;
import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Bean.HomePage.HomeNewestBean;
import net.youpo.Market.UI.AppListAdapter;
import net.youpo.Market.UI.AppInfo.AppInfoActivity;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.data.DataLoader;
import net.youpo.Market.data.ILoadDataResponse;
import net.youpo.Market.db.HomePage.HomeHottestTable;
import net.youpo.Market.db.HomePage.HomeNewestTable;

public class NewestByHomepageActivity extends BaseActivity {
	private ProgressDialog mLoadingDialog;
	private final String REQS_CONFIG = "Apps/Latest";
	private final int LOADING_DONE = 0;
	private final int ERROR = 1;
	private final int REFRESH_LIST = 516;

	private ListView mListView;
	private View loadingView;
	private ArrayList<AppInfoBean> mAppBeanList = new ArrayList<AppInfoBean>();
	private AppListAdapter mAdapter = new AppListAdapter(this, mAppBeanList);
	private DataLoader mDataLoader;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recommend_activity);
		mLoadingDialog = ProgressDialog.show(getParent(), "", "正在加载. 请等待...",
				true);
		mHandler.postDelayed(timeoutRunnalbe, ConstantsTable.TIMEOUT);
		init();
		mDataLoader = new DataLoader(this, REQS_CONFIG, dataResponse,
				HomeNewestTable.TABLE_NAME, HomeNewestTable.sql);
		mListView.setAdapter(mAdapter);// 必须放在addFooterView之后
	}

	private void init() {
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		loadingView = inflater.inflate(R.layout.loading_data, null);
		mListView = (ListView) this.findViewById(R.id.homepageRec_listview);
		mListView.setOnScrollListener(mScrollListener);
		mListView.setOnItemClickListener(mItemClickListener);

	}

	private void loadNext() {
		mListView.addFooterView(loadingView);
//		mListView.setAdapter(mAdapter);// 必须放在addFooterView之后
		mAdapter.notifyDataSetChanged();
		mDataLoader.loadNext();
	};

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case LOADING_DONE: {
				// AppManagerAdapter adapter = new AppManagerAdapter(
				// AppManagerActivity.this, mAppList);
				// mAppListView.setAdapter(adapter);
				mAdapter.notifyDataSetChanged();
				try {
					mListView.removeFooterView(loadingView);
				} catch (Exception e) {
					Log.e(ConstantsTable.LOG_TAG, "ClassCastException");
				}
				dissmissProgressDialog();
				break;
			}
			case REFRESH_LIST: {
				mAdapter.notifyDataSetChanged();
				break;
			}
			case ERROR: {
//				Toast.makeText(NewestByHomepageActivity.this, (String) msg.obj,
//						Toast.LENGTH_SHORT).show();
				// we should remove the loading footer view in either case;
				try {
					mListView.removeFooterView(loadingView);
				} catch (Exception e) {
					Log.e(ConstantsTable.LOG_TAG, "ClassCastException");
				}
				dissmissProgressDialog();
				break;
			}
			default:
			}

		}
	};

	/**
	 * 当Listview滑动的时候不会去下载缩略图，只有当滑动停止的时候才会下载缩略图。
	 */
	protected OnScrollListener mScrollListener = new OnScrollListener() {
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (firstVisibleItem + visibleItemCount < totalItemCount - 3)
				return;
			if (mDataLoader != null && mDataLoader.isLoading() == false
					&& mDataLoader.isEnd() == false) {
				loadNext();
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView arg0, int scrollState) {
			if (mAdapter == null) {
				return;
			}

			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_IDLE: // stop fling
				mAdapter.setFastFlingFlag(false);
				mAdapter.setDownloadThumbnailFlag(true);
				mHandler.sendEmptyMessageDelayed(REFRESH_LIST, REFRESH_LIST); // 700ms
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: // touch fling
				mAdapter.setFastFlingFlag(false);
				mAdapter.setDownloadThumbnailFlag(false);
				mHandler.removeMessages(REFRESH_LIST);
				break;
			case OnScrollListener.SCROLL_STATE_FLING: // fast fling
				mAdapter.setFastFlingFlag(true);
				mAdapter.setDownloadThumbnailFlag(false);
				mHandler.removeMessages(REFRESH_LIST);
				break;
			}
		}
	};

	ILoadDataResponse dataResponse = new ILoadDataResponse() {

		@Override
		public void onLoadDataComplete(ArrayList<AppInfoBean> nextAppInfo,
				int total, int current) {
			mHandler.removeCallbacks(timeoutRunnalbe);
			mAppBeanList.clear();
			mAppBeanList.addAll(nextAppInfo);
			System.out.println("tatal =" + total + "current =" + current);
			// use Handler.obtainMessage(),instead of msg = new Message();
			// because if there is already an Message object,that not be used by
			// any one ,the system will hand use that object,so you don't have
			// to
			// create and object and allocate memory.
			// it is also another example of object recycling and reusing in
			// android.
			Message msg = mHandler.obtainMessage();
			msg.what = LOADING_DONE;
			msg.obj = current + "/" + total + "songs";
			// this method is called from worker Thread,so we cannot update UI
			// from here.
			msg.sendToTarget();
		}

		@Override
		public void onLoadDataError(String errorMsg) {
			mHandler.removeCallbacks(timeoutRunnalbe);
			Message msg = mHandler.obtainMessage();
			msg.what = ERROR;
			msg.obj = errorMsg;
			msg.sendToTarget();
		}
	};

	OnItemClickListener mItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			if (mAppBeanList.size() > 0) {
				Intent intent = new Intent(NewestByHomepageActivity.this,
						AppInfoActivity.class);
				intent.putExtra(ConstantsTable.KEY_APPID,
						mAppBeanList.get(position).APP_ID);
				startActivity(intent);
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mAdapter != null) {
			mAdapter.recycle();
		}
		dissmissProgressDialog();
	}

	Runnable timeoutRunnalbe = new Runnable() {
		@Override
		public void run() {
			Message msg = mHandler.obtainMessage();
			msg.what = ERROR;
			msg.obj = "加载超时";
			msg.sendToTarget();
		}
	};
	
	private void dissmissProgressDialog() {
		if (mLoadingDialog != null && !isFinishing()
				&& mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
}
